var TOKEN_STR = "fingerplus";

var tool = require("./tool"),
    updateComposer = require("./updateComposer"),
    check = require("./check"),
    path = require("path"),
    crypto = require("crypto"),
    shasum = crypto.createHash('md5'),
    token = shasum.update(TOKEN_STR).digest("hex"),
    serverMap, serverArr, moduleName, username, urls;

module.exports = function (opt, fn) {

    moduleName = opt.modulename;
    username = opt.username;
    serverMap = opt.serverMap;
    serverArr = opt.serverArr;

    urls = serverMap.map(function (item) {
        return item.receiver;
    });

    check.checkServerIdle(urls.concat(), {
        type: 1,
        username: username,
        module: moduleName,
        token: token
    }, function () {
        updateComposer(serverMap.concat(), function () {
            fisp2Server(fn);
        }, function (err) {
            check.postToDel(serverMap.concat(), function () {
                process.exit(0);
            });
        }, true);
    });
};

function fisp2Server(fn) {
    var params = {
        type: 2,
        username: username,
        module: moduleName,
        token: token
    };

    rm("-rf", tool.PREFIX_PATH);
    console.log("\nfisp release to online server...".green);

    if (exec("fisp release -omp --domains -d " + serverArr.join(",")).code != 0) {
        console.log("\nError: Fisp release to server faild!");
        check.postToDel(urls.concat(), params, function () {
            process.exit(0);
        });
    } else {
        fn(function (callback) {
            check.postToDel(urls.concat(), params, function () {
                callback();
            })
        });
    }
}